// 通过类的方式进行封装，会让代码更具有复用性
import ur from '../utils/extendApi'
import {env} from './env'


class WxRequest {
  reqCount: any = 0
  setTimeOutFun: any = null
  // 默认参数
  defaults = {
    baseURL: '',//设置请求基准地址
    url: '',//设置请求路径
    data: null,//设置请求入参
    method: 'GET', //设置请求方式
    header: {
      'Content-type': 'application/json', //设置数据交互的格式
      'token':ur.getStorageApi('token')?ur.getStorageApi('token').replaceAll('"',''):''
    },
    timeout: 600000,//默认的超时时长，小程序的超时时长是1分钟
    isLoading:true,
  }

  // 定义默认的拦截器
  interceptors = {
    // 请求拦截器
    request: (config: any) => {
      return config
    },

    // 响应拦截器
    response: (response: any) => {
      return response
    }
  }


  constructor(params: any) {
    this.defaults = Object.assign({}, this.defaults, params)
  }


  request(options: any) {
    
    // 拼接完整的url
    options.url = this.defaults.baseURL + options.url
    // 合并请求参数
    options = { ...this.defaults, ...options }

    if (options.isLoading && options.method!=='UPLOAD') {
      if (this.reqCount === 0) {
        wx.showLoading({
          title: '处理中...'
        })
      }
      this.reqCount = this.reqCount + 1
    }

    options = this.interceptors.request(options)

    return new Promise((resolve: any, reject: any) => {
     
      if(options.method!=='UPLOAD'){
        wx.request({
          ...options,
          success: (res: any) => {
            resolve(this.interceptors.response({ ...res, config: options, isSuccess: true }))
          },
          fail: (error) => {
            reject(this.interceptors.response({ ...error, config: options, isSuccess: false }))
          },
          complete: () => {
            if(options.isLoading){
              this.reqCount = this.reqCount - 1
              this.reqCount === 0 && wx.hideLoading()
            }
          }
        })
      }else{
        wx.uploadFile({
          ...options,
          success:(res:any)=>{
            res.data=JSON.parse(res.data)
            resolve(this.interceptors.response({ ...res, config: options, isSuccess: true }))
          },
          fail:(error:any)=>{
            reject(this.interceptors.response({ ...error, config: options, isSuccess: false }))
          }
        })
      }
    


    })
  }

  get(url: any, data: any = {}, config: any = {}) {
    return this.request({
      url,
      data,
      method: 'GET',
      ...config
    })
  }

  delete(url: any, data: any = {}, config: any = {}) {
    return this.request({
      url,
      data,
      method: 'DELETE',
      ...config
    })
  }

  post(url: any, data: any = {}, config: any = {}) {
    return this.request({
      url,
      data,
      method: 'POST',
      ...config
    })
  }

  put(url: any, data: any = {}, config: any = {}) {
    return this.request({
      url,
      data,
      method: 'PUT',
      ...config
    })
  }

  upload(url,filePath,name,config:any={}){
    return this.request({
      url,
      filePath,
      name,
      method:'UPLOAD',
      ...config
    })
  }

  
}


const instance: any = new WxRequest({
  baseURL: env.baseUrl,
  timeout: 15000
})


// 重新配置自己的请求拦截器，可以在此处修改 请求入参
instance.interceptors.request = (config: any) => {
  // console.log('请求拦截器', config)
  // 如果本地有token，发请求就加上token
  const token: any = ur.getStorageApi('token')
  if (token) {
    config.token = token
  }
  return config
}


// 重新配置自己的响应拦截器，可以在此处修改 响应参数，或者判断参数做处理
instance.interceptors.response = async (response: any) => {
  // console.log('响应拦截器', response)

  // 请求的接口或者资源不存在
  if (response.statusCode === 404) {
    setTimeout(() => {
      ur.errToastApi({ title: '请求资源不存在' })
    }, 0);


    return Promise.reject(response)
  }

  // 请求接口正常
  if (response.data && response.data.code === 0 && response.statusCode === 200) {
    return response.data
  }

  // 请求接口正常
  if (response.data && response.data.code === -1) {
    setTimeout(() => {
      ur.errToastApi({ title: response.data.message })
    }, 0);
    return Promise.reject(response)
  }


  // 超时或者网络失败
  // if (!response.isSuccess) {
  //   ur.errToastApi({ title: '网络异常，请重试！！' })
  //   return Promise.reject(response)
  // }


  // 验证token失败
  if (response.data && response.data.code === 403) {
    const res: any = await ur.modalApi({ content: '鉴权失败，请重新登录', showCancel: false })
    if (res) {
      // 清除所有的本地储存，重新授权登录
      ur.clearStorageApi()
      ur.clearStorageApi()
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }
    return Promise.reject(response)
  }


  // 其他错误的情况
  setTimeout(() => {
    ur.errToastApi({ title: '系统程序异常，请联系管理员' })
  }, 0);
  return Promise.reject(response)
}


export default instance